<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Order extends Controller_Common {

	public $template='layout/index';

	public function emptyPost() {
		return array(
			'service_id' => '',
			'name' => '',
			'email' => '',
			'phone' => '',
			'content' => ''
		);
	}

	public function action_index() {
		$this->buildCarcas();

		$this->template->content = View::factory('pages/orderEmpty', array(
			'services' => ORM::factory('Services')->forSelect($this->postfix, 0),
			'post' => $this->emptyPost()
		));
	}

	public function action_one() {
		$this->buildCarcas();
		$obj = ORM::factory('Services')->getOne($this->postfix, $this->request->param('id'));
		$this->template->title = 'Zuber - '.$this->sitetext['application']['_value'].' - '.$obj->title.' - '.str_replace(',',' ',number_format($obj->price)).' kzt';
		$this->template->description = preg_replace('/<[^>]*>/', '', $obj->description);

		if (!empty($obj)) {
			$this->template->content = View::factory('pages/order', array(
				'current' => $obj,
			));
		} else {
			$this->redirect($this->lang.'/order');
		}
	}

	public function action_do() {
		$this->buildCarcas();
		$post = Validation::factory($_POST); // валидируем данные с формы

		$post->rule('service_id', 'not_empty')->rule('service_id', 'digit', array(':value', TRUE))
			->rule('name', 'not_empty')
			->rule('email', 'not_empty')->rule('email', 'email_domain')
			->rule('phone', 'not_empty')->rule('phone', 'phone');

		if ($post->check()) {
			$order = ORM::factory('Order');
			$order->service_id = $this->request->post('service_id');
			$order->name = $this->request->post('name');
			$order->email = $this->request->post('email');
			$order->phone = $this->request->post('phone');
			$order->content = $this->request->post('content');
			$order->creation_date = date('Y-m-d');
			$order->hash = md5($this->request->post('service_id').$this->request->post('name').$this->request->post('email').$this->request->post('phone').$this->request->post('content').date('Y-m-d'));

			try {
				$subscriber = ORM::factory('Subscribers');
				$subscriber->name = $this->request->post('name');
				$subscriber->email = $this->request->post('email');
				$subscriber->type = 1;
				$subscriber->save();
			} catch (Exception $e) {
				
			}

			try {
				$order->save();
				$this->template->content = View::factory('pages/message', array('message' => 'Спасибо за вашу заявку, наш менеджер свяжется с вами.'));

		        $config = Kohana::$config->load('email');
		        Email::connect($config);

		        $from = 'zeller.kz@gmail.com';
		        $to = Kohana::$config->load('main')->feedback_mail;
		        $subject = 'Zuber.kz - новый заказ';
		        $service = ORM::factory('Services')->getOne($this->postfix, $this->request->post('service_id'));
		        $message = '
		        	<div>Email: <a href="mailto:'.$this->request->post('email').'">'.$this->request->post('email').'</a></div>
		        	<div>Услуга: '.$service->title.'</div>
		        	<div>Имя или название компании: '.$this->request->post('name').'</div>
		        	<div>Телефон: '.$this->request->post('phone').'</div>
		        	<div>Сообщение:</div>
		        	<div>'.nl2br($this->request->post('content')).'</div>
		        ';

		        Email::send($to, $from, $subject, $message, $html = true);
			} catch (Exception $e) {
				$this->template->content = View::factory('pages/message', array('message' => 'Спасибо за вашу заявку, наш менеджер свяжется с вами.'));
			}
		} else {
			$this->template->content = View::factory('pages/orderEmpty', array(
				'errors' => $post->errors(),
				'services' => ORM::factory('Services')->forSelect($this->postfix, 0),
				'post' => $_POST
			));
		}
	}

}